package com.atguigu.ct.producer.bean;

import com.atguigu.ct.common.bean.DataIn;
import com.atguigu.ct.common.bean.DataOut;
import com.atguigu.ct.common.bean.Producer;
import com.atguigu.ct.common.util.DateUtil;
import com.atguigu.ct.common.util.NumberUtil;
import sun.rmi.runtime.Log;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * Description: 本地数据文件生产者
 * @Author: yyx
 * @Create: 2023/4/10 11:16
 * @Version: 8
 */
public class LocalFileProducer implements Producer {
    private DataIn in;
    private DataOut out;
    private volatile boolean flg = true;//增强内存可见性，在别的线程中改变了它的属性可以及时察觉

    public void setIn(DataIn in) {
        this.in = in;
    }

    public void setOut(DataOut out) {
        this.out = out;
    }

    /**
     * 生产数据
     */
    public void produce() {
        try{
            // 读取通讯录数据
            List<Contact> contacts = in.read(Contact.class);
            while (flg){
                // 从通讯录中随机查找2个电话号码（主叫，被叫）
                int call1Index = new Random().nextInt(contacts.size());
                int call2Index;
                while (true){
                    call2Index = new Random().nextInt(contacts.size());
                    if(call2Index != call1Index){
                        break;
                    }
                }
                Contact call1 = contacts.get(call1Index);
                Contact call2 = contacts.get(call2Index);
                // 生成随机的通话时间
                String startData = "20220101000000";
                String endData = "20230101000000";
                long startTime = DateUtil.parse(startData,"yyyyMMddHHmmss").getTime();
                long endTime = DateUtil.parse(endData,"yyyyMMddHHmmss").getTime();
                long callTime = startTime + (long)((endTime - startTime) * Math.random());//通话时间
                String callTimeString = DateUtil.format(new Date(callTime),"yyyyMMddHHmmss");//通话时间字符串
                // 生成随机的通话时长
                String duration = NumberUtil.format(new Random().nextInt(3000),4);//0189使得长度固定
                // 生成通话记录
                Calllog calllog = new Calllog(call1.getTel(),call2.getTel(),callTimeString,duration);
                System.out.println(calllog);
                // 将通话记录刷写到数据文件中
                out.write(calllog);
                Thread.sleep(500);//生成一条休眠0.5s
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 关闭生产者
     * @throws IOException
     */
    public void close() throws IOException {
        if(in != null){
            in.close();
        }
        if(out != null){
            out.close();
        }
    }
}
